﻿using System.IO;
using System.Xml.Serialization;
using SuppKids.Core.Providers;

namespace SuppKids.Core.Stuff
{
	public class StuffInfoStorage
	{
		private static readonly object syncRoot = new object();

		private readonly IApplicationSettingsProvider settings;

		private readonly XmlSerializer serializer = new XmlSerializer(typeof(StuffInfo));

		public StuffInfoStorage(IApplicationSettingsProvider settings)
		{
			this.settings = settings;
		}

		public StuffInfo Get()
		{
			if (!File.Exists(this.settings.PersonalInfoPath))
			{
				this.Set(new StuffInfo());
			}

			lock (syncRoot)
			{
				using (var stream = new FileStream(settings.PersonalInfoPath, FileMode.OpenOrCreate))
				{
					return (StuffInfo) serializer.Deserialize(stream);
				}
			}
		}

		public void Set(StuffInfo stuffInfo)
		{
			lock (syncRoot)
			{
				using (var stream = new FileStream(settings.PersonalInfoPath, FileMode.Create))
				{
					this.serializer.Serialize(stream, stuffInfo);
				}
			}
		}
	}
}